#include "file_read.h"

void initializeAndOpen(FileReader * reader, char * filename, int block_size)
{
  // Open file
  reader->file = fopen(filename, "rb");
  if(!reader->file) {
    reader->file = NULL;
    return;
  }

  // Get file size
  fseek(reader->file, 0, SEEK_END);
  reader->file_size = ftell(reader->file);
  fseek(reader->file, 0, SEEK_SET);

  // End of file check
  if(!reader->file_size) reader->at_end = 1;
  else reader->at_end = 0;

  // Other settings
  reader->block_size = block_size;
  reader->block_number = 0;
  reader->buffer = (char *) malloc(sizeof(char) * block_size);
}

int readBlock(FileReader * reader){
  int read = 0;

  // Cannot read at end of file
  if(reader->at_end)
    return 0;

  // Seek file cursor
  fseek(reader->file, reader->block_number * reader->block_size, SEEK_SET);

  // Read file
  read = fread(reader->buffer, sizeof(char), reader->block_size, reader->file);
  if(reader->block_number * reader->block_size + read >= reader->file_size)
    reader->at_end = 1;
  reader->block_number++;
  return read;
}

int readPreviousBlock(FileReader * reader)
{
  if(reader->block_number)
    reader->block_number--;
  return readBlock(reader);
}

void closeReader(FileReader * reader)
{
  fclose(reader->file);
  reader->file = NULL;
}

/*
int main()
{
  FileReader reader;
  int read = 0;
  initialize_and_open(&reader, "img.jpg", 512);
  if(!reader.file) {
    printf("File not found...\n");
    return -1;
  }
  FILE * file2;
  file2 = fopen("img2.jpg", "wb");
  while(!reader.at_end)
  {
    read = read_block(&reader);
    fwrite(reader.buffer, sizeof(char), read, file2);
  }
  close_reader(&reader);
  fclose(file2);
  return 0;
}
*/
